package services

import (
	"fmt"
	"git-hawk/internal/logic/dal"
	"git-hawk/internal/logic/models"
	"os"

	"fyne.io/fyne/v2"
	"github.com/go-git/go-git/v5"
)

type Application struct {
	Win         fyne.Window
	TreeTabData map[string]TreeTabInfo
}

// 左侧树形结构选项卡的信息
type TreeTabInfo struct {
	Info models.Project
	View func(w fyne.Window) fyne.CanvasObject
}

// 获取项目列表数据
func (app *Application) GetProject() []models.Project {
	list, err := dal.GetProject()
	if err != nil {
		fyne.LogError("获取项目列表数据失败", err)
	}
	return list
}

// 保存项目数据
func (app *Application) SaveProject(param *models.Project) {
	err := dal.SaveProject(param)
	if err != nil {
		fyne.LogError("修改项目失败", err)
	}
}

// 修改项目数据
func (app *Application) UpdateProject(param *models.Project) {
	err := dal.UpdateProject(param)
	if err != nil {
		fyne.LogError("修改项目失败", err)
	}
}

// 删除项目数据
func (app *Application) DeleteProject(id int) {
	err := dal.DeleteProject(id)
	if err != nil {
		fyne.LogError("删除项目失败", err)
	}
}

// 初始化新的Git仓库
func (app *Application) InitRepository(name, path string) (*git.Repository, error) {
	fullPath := path + "/" + name
	// 检查目录是否已存在
	if _, err := os.Stat(fullPath); os.IsNotExist(err) {
		// 创建目录
		if err := os.MkdirAll(fullPath, 0755); err != nil {
			return nil, fmt.Errorf("创建目录失败: %v", err)
		}
	}

	// 初始化仓库
	repo, err := git.PlainInit(fullPath, false)
	if err != nil {
		return nil, fmt.Errorf("初始化仓库失败: %v", err)
	}

	/* // 获取 HEAD 引用
	_, err = repo.Head()
	if err != nil {
		//初始化HEAD引用
		r := plumbing.NewHashReference(plumbing.HEAD, plumbing.NewBranchReferenceName("main"))
		if err := repo.Storer.SetReference(r); err != nil {
			panic(err)
		}
	} */

	projectParam := new(models.Project)
	projectParam.Name = name
	projectParam.Path = fullPath
	app.SaveProject(projectParam)

	return repo, nil
}
